<?php


namespace App\Api\Services;

use App\Api\Models\OrderLists;
use App\Api\Models\Seckill as SeckillModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Seckill
{
    //依据锁判断
    public function user($seckill_id, $uid)
    {
        if ($this->lock($uid)) {
            $this->goodsBuy($seckill_id, $uid);
            return true;
        } else {
            return false;
        }
    }

    //用户秒杀  剩余
    public function goodsBuy($seckill_id, $uid)
    {
        if (Redis::get('seckill' . $seckill_id) >= 1) {
            $remaining = Redis::decr('seckill' . $seckill_id);
            //价钱
            $price = SeckillModel::skInGood($seckill_id,'price');
            //放入队列
            $order = [
                'uid' => $uid,
                'type' => 1,
                'paid' => 0,
                'total_money'=>$price,
                'order_sn' => OrderBasic::orderSn(),
                'seckill_id' => $seckill_id,
                'order_time' => date('Y-m-d H:i:s', time())
            ];
            DB::beginTransaction();
            try {
                SeckillModel::inventoryReduction($seckill_id, $remaining);
                OrderLists::addOrder($order);
                DB::commit();
            } catch (\PDOException $e) {
                DB::rollBack();
            }
            return Redis::rpush("seckill" . $seckill_id . "list", json_encode($order));
        } else {
            return false;
        }
    }

    //加锁，判断锁
    public function lock($uid, $key = 'suo', $time = 300, $num = 3)
    {
        $is_lock = Redis::setnx($uid . $key, time() + $time);
        if (!$is_lock) {
            for ($i = 0; $i < $num; $i++) {
                $is_lock = Redis::setnx($uid . $key, time() + $time);
                if ($is_lock) {
                    break;
                }
            }
        }
        if (!$is_lock) {
            $lock_time = Redis::get($uid . $key);
            if (time() > $lock_time) {
                Redis::del($uid . $key);
                $is_lock = Redis::setnx($uid . $key, time() + $time);
            }
        }
        return $is_lock ? true : false;
    }

    //删除锁
    public function del($uid, $key = 'suo')
    {
        Redis::del($uid . $key);
    }
}